﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using BackgroundCopyManager;

namespace Klinkby.PodCaster.Model
{
    [Serializable]
    sealed class Post : IPost
    {
        Guid _jobId;

        public Post(string title, IEnumerable<Uri> urls)
        {
            Title = title;
            Urls = urls;
            FilePath = string.Empty;
        }

        #region IPost Members

        public string Title
        {
            get;
            private set;
        }

        public IEnumerable<Uri> Urls
        {
            get;
            private set;
        }

        DownloadStatus _oldDownloadStatus;
        public DownloadStatus DownloadStatus
        {
            get
            {
                if (_oldDownloadStatus == DownloadStatus.Completed)
                    return _oldDownloadStatus;
                var bits = new Bits();
                DownloadStatus downloadStatus;
                try
                {
                    downloadStatus = (_jobId == Guid.Empty)
                        ? DownloadStatus.New
                        : bits.GetState(_jobId) == BG_JOB_STATE.BG_JOB_STATE_TRANSFERRED
                            ? DownloadStatus.Completed
                            : DownloadStatus.Downloading;
                    if (_oldDownloadStatus != DownloadStatus.Completed && downloadStatus == DownloadStatus.Completed)
                    {
                        bits.Complete(_jobId);
                    }
                }
                catch (BitsException e)
                {
                    if (((COMException)e.InnerException).ErrorCode == unchecked((int)0x80200001)) // job not found, BITS propably cleaned up the job after completion
                    {
                        downloadStatus = DownloadStatus.Completed;
                    }
                    else
                        throw;
                }
                return _oldDownloadStatus = downloadStatus;
            }
        }

      
        static string GetFileName(Uri remotePath)
        {
            return remotePath.AbsoluteUri.Substring(remotePath.AbsoluteUri.LastIndexOf('/') + 1);
        }

        public IEnumerable<IDownloadInfo> GetDownloadInfo(string localDir)
        {
            return Urls.Select(url => (IDownloadInfo)new DownloadInfo(
                url,
                Path.Combine(localDir, GetFileName(url))
                ));
        }

        public void MarkDownloading(Guid jobId)
        {
            _jobId = jobId;
        }

        public string FilePath
        {
            get;
            private set;
        }

        #endregion
    }
}
